
#include "ButtonItem.h"
#include "hgeUtil.h"

#define BORDER 2

//
// Constructor
//

ButtonItem::ButtonItem(int _id, float x, float y, float width, float height, HTEXTURE pic, int totalPics, DWORD _selectColor)
{
	id = _id;

	selectedColor = _selectColor;
	unselectedColor = 0xFF808080;

	bStatic = false;
	bVisible = true;
	bEnabled = true;
	selected = false;

	rect.Set(x, y, x+width, y+height);

	button.v[0].x = x;
	button.v[0].y = y;
	button.v[1].x = x+width;
	button.v[1].y = y;
	button.v[2].x = x+width;
	button.v[2].y = y+height;
	button.v[3].x = x;
	button.v[3].y = y+height;
	
	image.v[0].x = x+BORDER;
	image.v[0].y = y+BORDER;
	image.v[1].x = x+width-BORDER;
	image.v[1].y = y+BORDER;
	image.v[2].x = x+width-BORDER;
	image.v[2].y = y+height-BORDER;
	image.v[3].x = x+BORDER;
	image.v[3].y = y+height-BORDER;

	image.blend = BLEND_ALPHABLEND | BLEND_COLORMUL | BLEND_NOZWRITE;
	button.blend = BLEND_ALPHABLEND | BLEND_COLORMUL | BLEND_NOZWRITE;

	for(int i = 0; i < 4; i++)
	{
		image.v[i].z  = 0.8f;
		image.v[i].col  = 0xFFFFFFFF;
		button.v[i].z  = 0.8f;
		button.v[i].col  = unselectedColor;
	}
	
	button.v[0].tx = 0; button.v[0].ty = 0;
	button.v[1].tx = 1; button.v[1].ty = 0;
	button.v[2].tx = 1; button.v[2].ty = 1;
	button.v[3].tx = 0; button.v[3].ty = 1;

	SetTexCoord(totalPics);

	image.tex = pic;
	button.tex = 0;
}

//
// SetTexCoord
//

void ButtonItem::SetTexCoord(int totalPics)
{
	image.v[0].tx = 0;
	image.v[1].tx = 1;
	image.v[2].tx = 1;
	image.v[3].tx = 0;

	if(totalPics == 1)
	{
		image.v[0].ty = 0;
		image.v[1].ty = 0;
		image.v[2].ty = 1;
		image.v[3].ty = 1;
	}
	else
	{
		float i = 1.0f / float(totalPics);
		image.v[0].ty = (id-1)*i;
		image.v[1].ty = (id-1)*i;
		image.v[2].ty = id*i;
		image.v[3].ty = id*i;
	}
}

//
// Render
//

void ButtonItem::Render()
{
	hge->Gfx_RenderQuad(&button);
	hge->Gfx_RenderQuad(&image);
}

//
// MouseLButton
//

bool ButtonItem::MouseLButton(bool bDown)
{
	if(bDown)
	{
		Select();
		return true;
	}
	return false;
}

//
// Select
//

void ButtonItem::Select()
{
	if(selected) return;
	selected = true;
	for(int i = 0; i < 4; i++)
		button.v[i].col  = selectedColor;
}

void ButtonItem::Unselect()
{
	if(!selected) return;
	selected = false;
	for(int i = 0; i < 4; i++)
		button.v[i].col  = unselectedColor;
}